package com.hdax.dm.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hdax.dm.entity.order.OrderTxMsg;
import com.hdax.dm.service.TxMsgService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;

@Component
public class MyConfirmCallback implements RabbitTemplate.ConfirmCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private TxMsgService txMsgService;

    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
    }
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        if(correlationData!=null) {
            String orderNo = correlationData.getId();
            QueryWrapper<OrderTxMsg> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", orderNo);
            OrderTxMsg msg = txMsgService.getOne(queryWrapper);
            if (msg.getBizType().equals("1") && msg.getMsgResult().equals("0")) {
                UpdateWrapper<OrderTxMsg> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("version", msg.getVersion() + 1);
                updateWrapper.set("msg_result", "1");
                updateWrapper.set("atime", LocalDateTime.now());
                updateWrapper.eq("id", orderNo);
                updateWrapper.eq("version", msg.getVersion());
                txMsgService.update(updateWrapper);
            }
        }
    }
}
